package com.yuwubao.uav.tool.util;

import com.alibaba.fastjson.JSONObject;
import com.yuwubao.framework.bean.PageData;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * Created by yangyu on 2017/10/27.
 */
@Configuration
public class ArticleSearchService {

    @Autowired
    private TransportClient client;

    /**
     * 创建一个文档
     */
    public Boolean createDoc(PageData pageData) throws Exception {
        String id = pageData.get("tableName").toString() + "_" + pageData.get("id").toString();
        XContentBuilder builder = XContentFactory.jsonBuilder()
                        .startObject()
                        .field("title", pageData.get("title")==null?pageData.get("name").toString():pageData.get("title").toString())
                        .field("author", pageData.get("author")==null?"":pageData.get("author").toString())
                        .field("content", pageData.get("content")==null?"":pageData.get("content").toString())
                        .field("img", pageData.get("img")==null?"":pageData.get("img").toString())
                        .field("dbId", pageData.get("id").toString())
                        .field("tableName", pageData.get("tableName")==null?"":pageData.get("tableName").toString())
                        .endObject();

//        IndexResponse indexResponse =
                this.client.prepareIndex()
                .setIndex("zk")
                .setType("article")
                .setId(id) // 如果没有设置id，则ES会自动生成一个id
                .setSource(builder.string())
                .get();
        return true;
    }


    /**
     * 更新文档
     *
     */
    public Boolean update(String id,PageData pageData)throws Exception{
        id = pageData.get("tableName").toString() + "_" + id;
        String article = get(id);
        if (article == null) {
            XContentBuilder builder = XContentFactory.jsonBuilder()
                    .startObject()
                    .field("title", pageData.get("title")==null?pageData.get("name").toString():pageData.get("title").toString())
                    .field("author", pageData.get("author")==null?"":pageData.get("author").toString())
                    .field("content", pageData.get("content")==null?"":pageData.get("content").toString())
                    .field("img", pageData.get("img")==null?"":pageData.get("img").toString())
                    .field("dbId", pageData.get("id").toString())
                    .field("tableName", pageData.get("tableName")==null?"":pageData.get("tableName").toString())
                    .endObject();

//        IndexResponse indexResponse =
            this.client.prepareIndex()
                    .setIndex("zk")
                    .setType("article")
                    .setId(id) // 如果没有设置id，则ES会自动生成一个id
                    .setSource(builder.string())
                    .get();
        } else {
            UpdateRequest update = new UpdateRequest("zk","article",id);
            String title = pageData.get("title")==null?pageData.get("name").toString():pageData.get("title").toString();
            String author = pageData.get("author")==null?"":pageData.get("author").toString();
            String content = pageData.get("content")==null?"":pageData.get("content").toString();
            String img = pageData.get("img")==null?"":pageData.get("img").toString();

            XContentBuilder builder = XContentFactory.jsonBuilder().startObject();
            if(!StringUtils.isEmpty(title)){
                builder.field("title",title);
            }
            if(!StringUtils.isEmpty(author)){
                builder.field("author", author);
            }
            if(!StringUtils.isEmpty(content)){
                builder.field("content", content);
            }
            if(!StringUtils.isEmpty(img)){
                builder.field("img", img);
            }
            builder.endObject();
            update.doc(builder);
//        UpdateResponse result =
            this.client.update(update).get();
        }

        return true;
    }

    /**
     * 根据ID查询一条数据记录。
     * @param id 要查询数据的ID。
     * @return 返回查询出来的记录对象的json字符串。
     */
    public String get(String id) {
        return this.client
                .prepareGet()    // 准备进行get操作，此时还有真正地执行get操作。（与直接get的区别）
                .setIndex("zk")  // 要查询的
                .setType("article")
                .setId(id)
                .get().getSourceAsString();
    }

    /**
     *  删除文档
     *
     */
    public Boolean delete(PageData pageData){
        String id = pageData.get("tableName").toString() + "_" + pageData.get("id").toString();
        DeleteResponse deleteResponse = client.prepareDelete("zk", "article",id).get();
        System.out.println("deleteResponse索引名称:" + deleteResponse.getIndex() + "\n deleteResponse类型:" + deleteResponse.getType()
                + "\n deleteResponse文档ID:" + deleteResponse.getId() + "\n当前实例deleteResponse状态:" + deleteResponse.status());
        return true;
    }





}
